import os
from os.path import join, abspath, dirname, splitext

import yaml

from library.api.parse import TParse
from library.api.security import Validation
from apps.auth.settings import config
from ldap3 import Server, Connection, ALL

current_path = dirname(abspath(__file__))

yml_json = {}

try:
    validate_yml_path = join(current_path, 'validations')
    for fi in os.listdir(validate_yml_path):
        if splitext(fi)[-1] != '.yml':
            continue
        with open(join(validate_yml_path, fi), 'rb') as f:
            yml_json.update(yaml.safe_load(f.read()))
except yaml.YAMLError as e:
    print(e)

v = Validation(yml_json)
validation = v.validation

p = TParse(yml_json)
parse_list_args = p.parse_list_args
parse_list_args2 = p.parse_list_args2
parse_json_form = p.parse_json_form
parse_pwd = p.parse_pwd


def check_ldap_login(name, password):
    server = Server(host=config.LDAP_HOST, port=config.LDAP_PORT, get_info=ALL)
    connection = Connection(server, config.LDAP_BASE_DN, config.LDAP_PASSWORD, auto_bind=True)
    response = connection.search(search_base=config.LDAP_SEARCH_DN, search_filter='(uid={})'.format(name),
                                 attributes=['userPassword'])
    if response:
        entry = connection.response[0]
        user_info_list = entry['attributes']['userPassword']
        for info in user_info_list:
            # query_password = str(info, 'utf-8')
            # if query_password == password:  # 密码是否一致
            if info:
                return name, password
    return None
